import { createRouter, createWebHistory } from 'vue-router'
import CourseDetail from '@/views/User/course/CourseDetail.vue'

// 系统管理相关页面
const Users = () => import('@/views/Admin/system/users.vue')

// 商品管理相关页面
const GoodsReturns = () => import('@/views/Admin/goods/returns.vue')
const GoodsCategories = () => import('@/views/Admin/goods/categories.vue')
const GoodsCreate = () => import('@/views/Admin/goods/create.vue')
const GoodsSelling = () => import('@/views/Admin/goods/selling.vue')
const GoodsWarehouse = () => import('@/views/Admin/goods/warehouse.vue')
// 订单管理相关页面
const OrdersCanceledUnpaid = () => import('@/views/Admin/orders/canceled-unpaid.vue')
const OrdersCanceledPaid = () => import('@/views/Admin/orders/canceled-paid.vue')
const OrdersCompleted = () => import('@/views/Admin/orders/completed.vue')
const OrdersUnprocessed = () => import('@/views/Admin/orders/unprocessed.vue')

// 会员管理相关页面
const MembersAccounts = () => import('@/views/Admin/members/accounts.vue')
const MembersConsumption = () => import('@/views/Admin/members/consumption.vue')
const MembersPoints = () => import('@/views/Admin/members/points.vue')
const MembersCoupons = () => import('@/views/Admin/members/coupons.vue')

// 其他页面组件
const AnnouncementsManage = () => import('@/views/Admin/announcements/manage.vue')
const CommentsUser = () => import('@/views/Admin/comments/user.vue')
const CustomerService = () => import('@/views/Admin/others/customer-service.vue')
const Feedback = () => import('@/views/Admin/others/feedback.vue')

// 会员中心相关页面
const MemberCenter = () => import('@/views/User/MemberCenter/MemberCenter.vue')
const AccountManagement = () => import('@/views/User/MemberCenter/AccountManagement/AccountManagement.vue')
const MessageNotification = () => import('@/views/User/MemberCenter/MessageNotification/MessageNotification.vue')
const Security = () => import('@/views/User/MemberCenter/Security/Security.vue')
const MyPoints = () => import('@/views/User/MemberCenter/MyPoints/MyPoints.vue')
const MyFavorites = () => import('@/views/User/MemberCenter/MyFavorites/MyFavorites.vue')
const MyFootprints = () => import('@/views/User/MemberCenter/MyFootprints/MyFootprints.vue')
const Transactions = () => import('@/views/User/MemberCenter/Transactions/Transactions.vue')
const OrderManagement = () => import('@/views/User/MemberCenter/Orders/OrderManagement.vue')
const Coupons = () => import('@/views/User/MemberCenter/Coupons/Coupons.vue')
const ServiceCenter = () => import('@/views/User/MemberCenter/ServiceCenter/ServiceCenter.vue')
const Returns = () => import('@/views/User/MemberCenter/AfterSales/returns.vue')
const HelpCenter = () => import('@/views/User/MemberCenter/Help-center/Help-center.vue')


const routes = [
  // 基础重定向
  {
    path: '/',
    redirect: '/login'
  },

  // 登录页
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Auth/LoginView.vue')
  },

  // 首页
  {
    path: '/home',
    name: 'Home',
    component: () => import('@/views/User/HomePage.vue'),
    meta: { requiresAuth: true }
  },

  // 注册页
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/Auth/RegisterView.vue')
  },

  // 用户订单管理页
  {
    path: '/orderManagement',
    name: 'OrderManagement',
    component: () => import('@/views/User/MemberCenter/Orders/OrderManagement.vue'),
    meta: { requiresAuth: true }
  },
  // 会员中心主页面
  {
    path: '/membercenter',
    name: 'MemberCenter',
    component: MemberCenter,
    redirect: '/membercenter/account',
    meta: { requiresAuth: true },
    children: [
      {
        path: 'account',
        name: 'AccountManagement',
        component: AccountManagement,
        meta: { title: '账号管理' }
      },
      {
        path: 'messages',
        name: 'MessageNotification',
        component: MessageNotification,
        meta: { title: '消息通知' }
      },
      {
        path: 'security',
        name: 'Security',
        component: Security,
        meta: { title: '账号安全' }
      },
      {
        path: 'points',
        name: 'MyPoints',
        component: MyPoints,
        meta: { title: '我的积分' }
      },
      {
        path: 'favorites',
        name: 'MyFavorites',
        component: MyFavorites,
        meta: { title: '我的收藏' }
      },
      {
        path: 'footprints',
        name: 'MyFootprints',
        component: MyFootprints,
        meta: { title: '我的足迹' }
      },
      {
        path: 'transactions',
        name: 'Transactions',
        component: Transactions,
        meta: { title: '交易管理' }
      },
      {
        path: 'order-management',
        name: 'OrderManagement',
        component: OrderManagement,
        meta: { title: '订单管理' }
      },
      {
        path: 'coupons',
        name: 'Coupons',
        component: Coupons,
        meta: { title: '优惠券' }
      },
      {
        path: 'service',
        name: 'ServiceCenter',
        component: ServiceCenter,
        meta: { title: '服务中心' }
      },
      {
        path: 'returns',
        name: 'Returns',
        component: Returns,
        meta: { title: '售后记录' }
      },
      {
        path: 'help-center',
        name: 'HelpCenter',
        component: HelpCenter,
        meta: { title: '帮助中心' }
      }
    ]
  },

  // 后台主布局页（带侧边栏和头部）
  {
    path: '/adminLayout',
    name: 'AdminLayout',
    component: () => import('@/views/Admin/AdminLayout.vue'),
    redirect: '/adminLayout/system/users', // 默认打开用户管理页
    meta: { requiresAuth: true },
    children: [
      // 系统管理
      {
        path: 'system/users',
        name: 'Users',
        component: Users
      },

      // 商品管理
      {
        path: 'goods/returns',
        name: 'GoodsReturns',
        component: GoodsReturns
      },
      {
        path: 'goods/categories',
        name: 'GoodsCategories',
        component: GoodsCategories
      },
      {
        path: 'goods/create',
        name: 'GoodsCreate',
        component: GoodsCreate
      },
      {
        path: 'goods/selling',
        name: 'GoodsSelling',
        component: GoodsSelling
      },
      {
        path: 'goods/warehouse',
        name: 'GoodsWarehouse',
        component: GoodsWarehouse
      },

      // 订单管理
      {
        path: 'orders/AllOrders',
        name: 'ordersAllOrders',
        component: () => import('@/views/Admin/orders/AllOrders.vue')
      },
      {
        path: 'orders/canceled-unpaid',
        name: 'OrdersCanceledUnpaid',
        component: OrdersCanceledUnpaid
      },
      {
        path: 'orders/canceled-paid',
        name: 'OrdersCanceledPaid',
        component: OrdersCanceledPaid
      },
      {
        path: 'orders/completed',
        name: 'OrdersCompleted',
        component: OrdersCompleted
      },
      {
        path: 'orders/unprocessed',
        name: 'OrdersUnprocessed',
        component: OrdersUnprocessed
      },

      // 会员管理
      {
        path: 'members/accounts',
        name: 'MembersAccounts',
        component: MembersAccounts
      },
      {
        path: 'members/consumption',
        name: 'MembersConsumption',
        component: MembersConsumption
      },
      {
        path: 'members/points',
        name: 'MembersPoints',
        component: MembersPoints
      },
      {
        path: 'members/coupons',
        name: 'MembersCoupons',
        component: MembersCoupons
      },

      // 公告管理
      {
        path: 'announcements/manage',
        name: 'AnnouncementsManage',
        component: AnnouncementsManage
      },

      // 评论管理
      {
        path: 'comments/user',
        name: 'CommentsUser',
        component: CommentsUser
      },

      // 客服与反馈
      {
        path: 'others/customer-service',
        name: 'CustomerService',
        component: CustomerService
      },
      {
        path: 'others/feedback',
        name: 'Feedback',
        component: Feedback
      }
    ]
  },

  // 帮助中心
  {
    path: '/helpCenter',
    name: 'HelpCenter',
    component: () => import('@/views/Auth/HelpCenter.vue'),
    meta: { requiresAuth: true }
  },

  // 购物车
  {
    path: '/shoppingcart',
    name: 'ShoppingCart',
    component: () => import('@/views/User/ShoppingCart/ShoppingCart.vue'),
    meta: { requiresAuth: true }
  },

  // 结算页
  {
    path: '/checkout',
    name: 'Checkout',
    component: () => import('@/views/User/ShoppingCart/Checkout.vue')
  },

  // 支付页
  {
    path: '/payment',
    name: 'Payment',
    component: () => import('@/views/User/ShoppingCart/Payment.vue'),
    meta: { requiresAuth: true }
  },

  // 第三方支付页
  {
    path: '/third-party-payment',
    name: 'ThirdPartyPayment',
    component: () => import('@/views/User/ShoppingCart/ThirdPartyPayment.vue')
  },

  // 订单详情页
  {
    path: '/order-detail',
    name: 'OrderDetail',
    component: () => import('@/views/User/MemberCenter/Orders/OrderDetail.vue')
  },

  // 所有订单页
  {
    path: '/allorders',
    name: 'AllOrders',
    component: () => import('@/views/Admin/orders/AllOrders.vue')
  },

  // 在线客服
  {
    path: '/support',
    name: 'Support',
    component: () => import('@/views/Auth/Support.vue'),
    meta: { requiresAuth: true }
  },

  // 热门课程排行榜
  {
    path: '/hotcourse-ranking',
    name: 'HotCourseRanking',
    component: () => import('@/views/User/course/HotCourseRanking.vue')
  },

  // 课程详情
  {
    path: '/course/:id',
    name: 'CourseDetail',
    component: CourseDetail
  }
]

const router = createRouter({
  history: createWebHistory('/'),
  routes
})

export default router

// // 路由守卫：权限控制
// router.beforeEach((to, from, next) => {
//   const isLoggedIn = !!localStorage.getItem('token') // 假设 token 存在 localStorage 中

//   if (to.meta.requiresAuth && !isLoggedIn) {
//     next({ name: 'Login' }) // 需要登录且未登录，则跳转至登录页
//   } else {
//     next()
//   }
// })



// import { createRouter, createWebHashHistory } from 'vue-router'
// import { useUserStore } from '@/stores/user'
// import { ElMessage } from 'element-plus'

// // 公共路由，不需要权限可访问
// export const constantRoutes = [
//   {
//     path: '/',
//     redirect: '/login'
//   },
//   {
//     path: '/login',
//     name: 'Login',
//     component: () => import('@/views/LoginView.vue'),
//     meta: { title: '登录', noAuth: true }
//   },
//   {
//     path: '/register',
//     name: 'Register',
//     component: () => import('@/views/RegisterView.vue'),
//     meta: { title: '注册', noAuth: true }
//   },
//   // {
//   //   path: '/forgot-password',
//   //   name: 'ForgotPassword',
//   //   component: () => import('../views/forgot-password/index.vue'),
//   //   meta: { title: '忘记密码', noAuth: true }
//   // },
 
//   // {
//   //   path: '/404',
//   //   component: () => import('../views/error/404.vue'), // 需要创建此页面
//   //   meta: { title: '404', noAuth: true }
//   // },
//   // 添加默认首页路由，不需要权限
  
    
  
//   // 个人中心路由，添加到通用布局中
//   //TODO 加验证
//   // {
//   //   path: '/personalcenter',
//   //   component: () => import('../layout/index.vue'),
//   //   children: [
//   //     {
//   //       path: '',
//   //       name: 'PersonalCenter',
//   //       component: () => import('../views/personalcenter.vue'),
//   //       meta: { title: '个人中心', icon: 'User' }
//   //     }
//   //   ]
//   // }
// ]

// // 创建路由实例
// const router = createRouter({
//   history: createWebHashHistory(),
//   routes: constantRoutes
// })

// // 白名单，不需要登录就可访问的路径
// const whiteList = ['/login', '/register', '/forgot-password']

// // 路由守卫
// router.beforeEach(async (to, from, next) => {
//   // 设置页面标题
//   document.title = to.meta.title ? `${to.meta.title} - 录课商城管理系统` : '录课商城管理系统'

//   // 获取用户信息
//   const userStore = useUserStore()
//   const hasLogin = userStore.isLogin

//   // 如果已经登录
//   if (hasLogin) {
//     if (to.path === '/login') {
//       // 如果是登录页，重定向到首页
//       next({ path: '/home' })
//     } else {
//       // 判断路由是否添加过
//       const { menuTree } = userStore

//       // 动态导入权限store（避免循环依赖）
//       let permissionStore = null
//       try {
//         const module = await import('../stores/permission')
//         permissionStore = module.usePermissionStore()
//       } catch (e) {
//         console.error('加载权限模块失败:', e)
//         next()
//         return
//       }

//       // 如果没有菜单数据，或者动态路由尚未添加
//       if (menuTree && menuTree.length > 0 && permissionStore.addRoutes.length === 0) {
//         try {
//           // 生成路由
//           const accessRoutes = await permissionStore.generateRoutes()

//           // 移除可能存在的旧路由（解决用户切换问题）
//           permissionStore.addRoutes.forEach(route => {
//             if (router.hasRoute(route.name)) {
//               router.removeRoute(route.name)
//             }
//           })

//           // 动态添加路由
//           accessRoutes.forEach(route => {
//             if (!router.hasRoute(route.name)) {
//               router.addRoute(route)
//             }
//           })

//           // 404 路由必须放在最后
//           if (router.hasRoute('catchAll')) {
//             router.removeRoute('catchAll')
//           }
//           router.addRoute({
//             path: '/:pathMatch(.*)',
//             name: 'catchAll',
//             redirect: '/404'
//           })

//           // 重新导航到目标路由，replace: true 是为了不留下重定向的历史记录
//           next({ ...to, replace: true })
//         } catch (error) {
//           // 路由生成失败
//           console.error('路由生成失败', error)
//           ElMessage.error('系统路由加载失败，请重新登录')
//           userStore.logout()
//           next('/login')
//         }
//       } else {
//         // 已经添加了动态路由，直接进入
//         next()
//       }
//     }
//   } else {
//     // 没有登录
//     if (whiteList.includes(to.path)) {
//       // 在白名单中，直接进入
//       next()
//     } else {
//       // 不在白名单中，重定向到登录页
//       next(`/login`)
//     }
//   }
// })

// export default router
